/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ps.yj.y1j0.rest;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.jboss.resteasy.annotations.Form;
import org.jboss.resteasy.annotations.cache.NoCache;
import ps.yj.y1j0.business.KVData.YJKVDataHandler;
import ps.yj.y1j0.business.KVData.YJKVDataObject;
import ps.yj.y1j0.data.YJResult;
import ps.yj.y1j0.business.YJDataHandler;
import ps.yj.y1j0.business.YJWriteToFile;

import java.sql.SQLException;

/**
 * @author yanjun
 */
@Path("/post")
@NoCache
public class YJRestPost {
    @POST
    @Path("/config")
    @Produces(MediaType.APPLICATION_JSON)
    public YJResult saveToFile(@FormParam("name") String name, @FormParam("content") String content) {
        YJResult result = new YJResult();
        try {
            YJWriteToFile writer = YJWriteToFile.getInstance();
            Boolean r = writer.write(name, content);
            if (r && !name.equals("menu.json")) {
                YJDataHandler handler = new YJKVDataHandler(name.split("\\.")[0], "rowid");
                if (handler.check()) {
                    handler.drop();
                }
            }
            result.setStatus(r);
            result.setMessage(r ? "文件写入成功！" : "文件写入失败！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(Boolean.FALSE);
            result.setMessage("文件写入失败！");
        } finally {
            return result;
        }
    }

    @POST
    @Path("/kv")
    @Produces(MediaType.APPLICATION_JSON)
    public YJResult addKVData(@Form YJKVDataObject data) {
        YJResult resultData = new YJResult();
        YJDataHandler handler = new YJKVDataHandler(data.getDataKind(), "rowid");
        int result = 0;
        if (!handler.check()) {
            if (handler.create(data.properties())) {
                result = handler.insert(data);
            }
        } else {
            result = handler.insert(data);
        }
        resultData.setStatus(result > 0 ? Boolean.TRUE : Boolean.FALSE);
        resultData.setMessage(result > 0 ? "新增成功！" : "新增失败！");
        return resultData;
    }
}
